/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("Luxs_rfq",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using MyErp.IServices;
using VOL.Core.Utilities;
using VOL.Core.DBManager;
using Microsoft.AspNetCore.Authorization;
using System.Collections;
using System.Linq;
using VOL.Core.ManageUser;
using MyErp.Repositories;
using MyErp.IRepositories;
using System.Text.RegularExpressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using VOL.Core.WorkFlow;

namespace MyErp.Controllers
{
    public partial class Luxs_rfqController
    {
        private readonly ILuxs_rfqService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public Luxs_rfqController(
            ILuxs_rfqService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        private WebResponseContent webResponse = new WebResponseContent();
        [HttpPost, Route("New_rfq")]//,AllowAnonymous
        public WebResponseContent New_rfq(string part_nos, string supper_nos)
        {
            //Console.WriteLine(part_nos);
            string[] part_nos_array = part_nos.Split(',');
            string[] supper_nos_array = supper_nos.Split(',');
            string now_d = DateTime.Now.ToString("yyMMdd").ToString();
            string yy = now_d.ToString().Substring(0, 2);
            string mm = now_d.ToString().Substring(2, 2);
            string dd = now_d.ToString().Substring(4, 2);
            //用到了Convert.ToDateTime，先转换为list表后再，where中使用Convert.ToDateTime，否则报错
            int co = 0;
            try//报错后继续执行，因为数据库中可能没有数据，所以报错
            {
                co = DBServerProvider.DbContext.Set<Luxs_rfq>().ToList().Where(w => Convert.ToDateTime(w.CreateDate).ToString("yyMMdd") == now_d).Select(s => s.rfq_no.Substring(11).ToInt()).Max();//从当日的最大值开始
            }
            catch (Exception)
            {  
                co = 0;
            }
            // int co = DBServerProvider.DbContext.Set<Luxs_rfq>().Where(w => Convert.ToDateTime(w.CreateDate).ToString("yyMMdd") == now_d).ToList().Count();
            foreach (var part in part_nos_array)
            {
                foreach (var supp in supper_nos_array)
                {
                    co = co + 1;
                    Luxs_rfq luxs_Rfq = new Luxs_rfq();
                    luxs_Rfq.part_no = part;
                    luxs_Rfq.supp_no = supp;
                    luxs_Rfq.ishiddencust = 1;
                    luxs_Rfq.ishiddenpname = 1;
                    luxs_Rfq.CreateDate = DateTime.Now;
                    luxs_Rfq.Creator = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserTrueName;//用户真实名称
                    luxs_Rfq.CreateID = UserContext.Current.UserId;
                    luxs_Rfq.rfq_no = "RFQ-" + yy + mm + dd + "-" + co;
                    DBServerProvider.DbContext.Update(luxs_Rfq);


                    WorkFlowManager.AddProcese(luxs_Rfq);//启动一个新审批任务
                    //以下代码手工产生流程数据，新增数据不是使用框架的，所以需要手工增加启动流程，注意手工启动时需要填入Luxs_rfq表名
                   /* string workTable = typeof(Luxs_rfq).GetEntityTableName();
                        Sys_WorkFlow workFlow = DBServerProvider.DbContext.Set<Sys_WorkFlow>()
                    .Where(x => x.WorkTable == workTable)
                     .Include(x => x.Sys_WorkFlowStep)
                    .FirstOrDefault();
                   // Guid guid = new Guid("12E4D09E-E110-427F-9C0C-D35825F96CD9");//业务流程编码 Sys_WorkFlow
                    Guid workFlowTable_Id = Guid.NewGuid();
                    Sys_WorkFlowTable sys_WorkFlowTable = new Sys_WorkFlowTable()
                    {
                        WorkFlowTable_Id = workFlowTable_Id,
                        WorkFlow_Id = workFlow.WorkFlow_Id,
                        WorkName = workFlow.WorkName,
                        WorkTable = workTable,
                        WorkTableKey = typeof(Luxs_rfq).GetKeyProperty().GetValue(luxs_Rfq).ToString(),
                        WorkTableName = workFlow.WorkTableName,
                        CurrentOrderId = 1,
                        Enable = 1,
                        CreateID = UserContext.Current.UserId,
                        CreateDate = DateTime.Now,
                        Creator = UserContext.Current.UserTrueName,
                        Sys_WorkFlowTableStep = workFlow.Sys_WorkFlowStep.OrderBy(x => x.OrderId).Select(s => new Sys_WorkFlowTableStep()
                        {
                            Sys_WorkFlowTableStep_Id = Guid.NewGuid(),    
                            WorkFlowTable_Id = workFlowTable_Id,
                            WorkFlow_Id = s.WorkFlow_Id,
                            StepId = s.StepId,
                            StepName = s.StepName,
                            AuditId = s.StepType == (int)AuditType.用户审批 ? s.StepValue : null,
                            StepType = s.StepType,
                            StepValue = s.StepValue,
                            OrderId = s.OrderId,
                            Enable = 1,
                            CreateDate = DateTime.Now,
                        }).ToList()

                    };
                    DBServerProvider.DbContext.Set<Sys_WorkFlowTable>().Add(sys_WorkFlowTable);
                    DBServerProvider.DbContext.SaveChanges();  */

                }
            }
            DBServerProvider.DbContext.SaveChanges();

            return webResponse.OK("生成RFQ成功！");
        }
        /// <summary>
        /// 获取RFQ签收页面数据
        /// </summary>
        /// <param name="rfq_no"></param>
        /// <returns></returns>
        [HttpPost, Route("get_rfq_all"), AllowAnonymous]//,AllowAnonymous
        public object get_rfq_all(string rfq_no)
        {
            Hashtable rtn_hst = new Hashtable();

            Luxs_rfq luxs_rfq = new Luxs_rfq();
            luxs_rfq = DBServerProvider.DbContext.Set<Luxs_rfq>().Where(s => s.rfq_no == rfq_no).FirstOrDefault();
            rtn_hst.Add("luxs_rfq", luxs_rfq);

            Erp_mara mara = new Erp_mara();
            mara = DBServerProvider.DbContext.Set<Erp_mara>().Where(s => s.matnr == luxs_rfq.part_no).FirstOrDefault();
            rtn_hst.Add("mara", mara);

            Erp_supper supper = new Erp_supper();
            supper = DBServerProvider.DbContext.Set<Erp_supper>().Where(s => s.lifnr == luxs_rfq.supp_no).FirstOrDefault();
            rtn_hst.Add("supper", supper);

            Luxs_project project = new Luxs_project();

            //Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt(); //接受清单没有的先插入,是为后面可以再修改

            int part_js_co_rec_cout = DBServerProvider.SqlDapper.QueryList<int>("select count(*) from luxs_part_js_rec_view where rfq_no=@rfq_no", new { rfq_no }).ToList()[0];
            if (part_js_co_rec_cout == 0)//零件技术要求
            {
                insert_get_last_part_js(rfq_no, mara.mara_id);
                //Luxs_js_for_mara luxs_Js_For_Mara = new Luxs_js_for_mara();
            }

            int luxs_pro_req_rec_view_count = DBServerProvider.SqlDapper.QueryList<int>("select count(*) from luxs_pro_req_rec_view where rfq_no=@rfq_no", new { rfq_no }).ToList()[0];
            if (luxs_pro_req_rec_view_count == 0)//项目要求
            {
                /*Guid[] project_id_array = DBServerProvider.DbContext.Set<Luxs_view_project_for_mara>().Where(s => s.mara_id == mara.mara_id).Select(s => s.luxs_project_id).ToArray();//物料=》项目
                List<Luxs_req_for_project> list_luxs_req_for_project = DBServerProvider.DbContext.Set<Luxs_req_for_project>().Where(w => project_id_array.Contains(w.luxs_project_id)).ToList();//项目=》项目要求
                foreach (var item in list_luxs_req_for_project)
                {
                    Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt();
                    luxs_Rfq_Receipt.rfq_no = rfq_no;
                    luxs_Rfq_Receipt.receipt_id = item.luxs_req_for_project_id;//项目要求uuid
                    DBServerProvider.DbContext.Add(luxs_Rfq_Receipt);
                };
                DBServerProvider.DbContext.SaveChanges();*/
                insert_project_req_list(rfq_no, mara.mara_id);


            }

            int luxs_cust_tx_rec_view_count = DBServerProvider.SqlDapper.QueryList<int>("select count(*) from luxs_cust_tx_rec_view where rfq_no=@rfq_no", new { rfq_no }).ToList()[0];
            if (luxs_cust_tx_rec_view_count == 0)//客户特殊要求
            {
                insert_cutomer_ts_list(rfq_no, mara.mara_id);
                /*Guid[] project_id_array = DBServerProvider.DbContext.Set<Luxs_view_project_for_mara>().Where(s => s.mara_id == mara.mara_id).Select(s => s.luxs_project_id).ToArray();//物料=》项目
                string[] customer_id_array = DBServerProvider.DbContext.Set<Luxs_project>().Where(s => project_id_array.Contains(s.luxs_project_id)).Select(s => s.customer_id).ToArray();//项目=》客户，注意customer_id是存多个Guid，所以只能字符串
                List<Guid> all_customer_id_list = new List<Guid>();
               // Guid[] all_customer_id_array=new Guid[] { };
                if (customer_id_array.Count() > 0)
                {
                    foreach (var item in customer_id_array)//因为项目中的客户字段存的"sdfsd,sdfsdf",所以要循环
                    {
                        if (item.ToString().IndexOf(",") > 0)
                        {
                            foreach (var xx in item.Split(","))
                            {
                                Guid guid = new Guid(xx);//string转为Guid
                                all_customer_id_list.Add(guid);
                            }
                        }
                        else
                        {
                            Guid guid = new Guid(item);//string转为Guid
                            all_customer_id_list.Add(guid);
                        }
                    }
                }
                List<Luxs_tx_for_customer> list_Luxs_tx_for_customer = DBServerProvider.DbContext.Set<Luxs_tx_for_customer>().Where(w => all_customer_id_list.Contains(w.luxs_customer_id)).ToList();//客户特殊要求
                foreach (var item in list_Luxs_tx_for_customer)
                {
                    Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt();
                    luxs_Rfq_Receipt.rfq_no = rfq_no;
                    luxs_Rfq_Receipt.receipt_id = item.luxs_tx_for_customer_id;//客户特殊要求uuid
                    DBServerProvider.DbContext.Add(luxs_Rfq_Receipt);
                };
                DBServerProvider.DbContext.SaveChanges();*/

            }
            return rtn_hst;
        }
        /// <summary>
        /// 签收rfq
        /// </summary>
        /// <param name="luxs_rfq_receipt_id"></param>
        /// <param name="ls_type"></param>
        /// <returns></returns>
        [HttpPost, Route("handle_rfq"),AllowAnonymous]//
        public  WebResponseContent handle_rfq(Guid luxs_rfq_receipt_id,string ls_type)
        {
            Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt();
            luxs_Rfq_Receipt.luxs_rfq_receipt_id = luxs_rfq_receipt_id;
            luxs_Rfq_Receipt.h_datetime=System.DateTime.Now;
            string loginid = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserTrueName;
            if (ls_type == "a")
            {
                luxs_Rfq_Receipt.status = "接受";
            }
            else
            {
                luxs_Rfq_Receipt.status = "拒绝";
            }
            luxs_Rfq_Receipt.handler = loginid;
            ILuxs_rfq_receiptRepository repository = Luxs_rfq_receiptRepository.Instance;
            repository.Update(luxs_Rfq_Receipt, x =>new { x.status,x.h_datetime,x.handler }, true);
            
            return webResponse.OK();
        }
       /// <summary>
       /// 获取最新的零件技术清单
       /// </summary>
       /// <param name="rfq_no"></param>
       /// <returns></returns>
        [HttpPost, Route("get_last_part_js"), AllowAnonymous]
        public WebResponseContent get_last_part_js(string rfq_no)
        {
            //先根据rfq_no和luxs_rfq_receipt_id删除表Luxs_rfq_receipt
            Luxs_rfq luxs_rfq = new Luxs_rfq();
            luxs_rfq = DBServerProvider.DbContext.Set<Luxs_rfq>().Where(s => s.rfq_no == rfq_no).FirstOrDefault();

            Erp_mara mara = new Erp_mara();
            mara = DBServerProvider.DbContext.Set<Erp_mara>().Where(s => s.matnr == luxs_rfq.part_no).FirstOrDefault();
            
            Guid[] luxs_rfq_receipt_id_s = DBServerProvider.DbContext.Set<Luxs_part_js_rec_view>().Where(w => w.rfq_no == rfq_no).Select(s=>s.luxs_rfq_receipt_id).ToArray();
            Luxs_rfq_receipt[] keys=DBServerProvider.DbContext.Set<Luxs_rfq_receipt>().Where(w => w.rfq_no == rfq_no && luxs_rfq_receipt_id_s.Contains(w.luxs_rfq_receipt_id)).ToArray();
            DBServerProvider.DbContext.Set<Luxs_rfq_receipt>().RemoveRange(keys);

            insert_get_last_part_js(rfq_no, mara.mara_id);
            return webResponse.OK();
        }

        

        private void insert_get_last_part_js(string rfq_no,Guid mara_id)
        {
            List<Luxs_js_for_mara> list_part_mara = DBServerProvider.DbContext.Set<Luxs_js_for_mara>().Where(s => s.mara_id == mara_id).ToList();
            foreach (var item in list_part_mara)
            {
                Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt();
                luxs_Rfq_Receipt.rfq_no = rfq_no;
                luxs_Rfq_Receipt.receipt_id = item.luxs_js_for_mara_id;//零件技术资料uuid
                DBServerProvider.DbContext.Add(luxs_Rfq_Receipt);
            };
            DBServerProvider.DbContext.SaveChanges();
        }

        private void insert_project_req_list(string rfq_no, Guid mara_id)
        {
            Guid[] project_id_array = DBServerProvider.DbContext.Set<Luxs_view_project_for_mara>().Where(s => s.mara_id == mara_id).Select(s => s.luxs_project_id).ToArray();//物料=》项目
            List<Luxs_req_for_project> list_luxs_req_for_project = DBServerProvider.DbContext.Set<Luxs_req_for_project>().Where(w => project_id_array.Contains(w.luxs_project_id)).ToList();//项目=》项目要求
            foreach (var item in list_luxs_req_for_project)
            {
                Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt();
                luxs_Rfq_Receipt.rfq_no = rfq_no;
                luxs_Rfq_Receipt.receipt_id = item.luxs_req_for_project_id;//项目要求uuid
                DBServerProvider.DbContext.Add(luxs_Rfq_Receipt);
            };
            DBServerProvider.DbContext.SaveChanges();
        }

        private void insert_cutomer_ts_list(string rfq_no, Guid mara_id)
        {
            Guid[] project_id_array = DBServerProvider.DbContext.Set<Luxs_view_project_for_mara>().Where(s => s.mara_id == mara_id).Select(s => s.luxs_project_id).ToArray();//物料=》项目
            string[] customer_id_array = DBServerProvider.DbContext.Set<Luxs_project>().Where(s => project_id_array.Contains(s.luxs_project_id)).Select(s => s.customer_id).ToArray();//项目=》客户，注意customer_id是存多个Guid，所以只能字符串
            List<Guid> all_customer_id_list = new List<Guid>();
            // Guid[] all_customer_id_array=new Guid[] { };
            if (customer_id_array.Count() > 0)
            {
                foreach (var item in customer_id_array)//因为项目中的客户字段存的"sdfsd,sdfsdf",所以要循环
                {
                    if (item.ToString().IndexOf(",") > 0)
                    {
                        foreach (var xx in item.Split(","))
                        {
                            Guid guid = new Guid(xx);//string转为Guid
                            all_customer_id_list.Add(guid);
                        }
                    }
                    else
                    {
                        Guid guid = new Guid(item);//string转为Guid
                        all_customer_id_list.Add(guid);
                    }
                }
            }
            List<Luxs_tx_for_customer> list_Luxs_tx_for_customer = DBServerProvider.DbContext.Set<Luxs_tx_for_customer>().Where(w => all_customer_id_list.Contains(w.luxs_customer_id)).ToList();//客户特殊要求
            foreach (var item in list_Luxs_tx_for_customer)
            {
                Luxs_rfq_receipt luxs_Rfq_Receipt = new Luxs_rfq_receipt();
                luxs_Rfq_Receipt.rfq_no = rfq_no;
                luxs_Rfq_Receipt.receipt_id = item.luxs_tx_for_customer_id;//客户特殊要求uuid
                DBServerProvider.DbContext.Add(luxs_Rfq_Receipt);
            };
            DBServerProvider.DbContext.SaveChanges();
        }

        /// <summary>
        /// 获取全部签收清单
        /// </summary>
        /// <param name="rfq_no"></param>
        /// <returns></returns>
        [HttpPost, Route("get_all_req_list"), AllowAnonymous]
        public WebResponseContent get_all_req_list(string rfq_no)
        {
            Luxs_rfq_receipt[] keys = DBServerProvider.DbContext.Set<Luxs_rfq_receipt>().Where(w => w.rfq_no == rfq_no).ToArray();
            DBServerProvider.DbContext.Set<Luxs_rfq_receipt>().RemoveRange(keys);
            Luxs_rfq luxs_rfq = new Luxs_rfq();
            luxs_rfq = DBServerProvider.DbContext.Set<Luxs_rfq>().Where(s => s.rfq_no == rfq_no).FirstOrDefault();

            Erp_mara mara = new Erp_mara();
            mara = DBServerProvider.DbContext.Set<Erp_mara>().Where(s => s.matnr == luxs_rfq.part_no).FirstOrDefault();
            insert_get_last_part_js(rfq_no, mara.mara_id);
            insert_project_req_list(rfq_no, mara.mara_id);
            insert_cutomer_ts_list(rfq_no, mara.mara_id);

            return webResponse.OK();
        }


    }
}
;